package main

import (
	"fmt"
	"gitee.com/xiangxiaoc/bodyfat-rate-ranking/mutex/service"
	"log"
	"math/rand"
	"time"
)

func main() {
	// 实例一个体脂率排行榜服务
	s := &service.BodyFatRateRankingService{}

	// 启动 1000 个 goroutine 模拟 1000 名用户同时使用服务
	for i := 0; i < 1000; i++ {
		username := fmt.Sprintf("user_%d", i+1)
		go register(s, username)
		go updateUserBodyFatRate(s, username)
		go getRanking(s, username)
	}

	// 服务运行 30 秒来演示
	time.Sleep(30 * time.Second)
}

func getRanking(s *service.BodyFatRateRankingService, username string) {
	for {
		ranking := s.GetRanking(username)
		log.Printf("[用户端日志] %s 用户查询自己的排名为：%d", username, ranking)
		time.Sleep(600 * time.Millisecond)
	}
}

func updateUserBodyFatRate(s *service.BodyFatRateRankingService, username string) {
	for {
		rand.Seed(time.Now().UnixNano())
		rate := rand.Float64() * 0.4
		s.UpdateUserBodyFatRate(username, rate)
		log.Printf("[用户端日志] %s 用户更新体脂率完成，立即返回当前排名：%v", username, s.GetRanking(username))
		time.Sleep(800 * time.Millisecond)
	}
}

func register(s *service.BodyFatRateRankingService, username string) {
	s.Register(username)
}
